package com.pj.znt.service;

import com.pj.project.sys_client.SysClientMapper;
import com.pj.project4sp.config.SpConfigUtil;
import com.pj.utils.sg.AjaxJson;
import com.pj.znt.config.ChatConfig;
import com.pj.znt.domain.entity.FastGptTopic;
import com.pj.znt.domain.query.ChatRequest;
import com.pj.znt.enums.ApiEndpoint;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;

/**
 * 聊天服务类，处理与聊天API相关的业务逻辑。
 *
 * @author 耿佳豪
 * @version 1.0
 * @since 2024-11-21
 */
@Slf4j
@Service
public class ChatService {

    @Autowired
    private ChatConfig chatConfig;
    @Autowired
    private SysClientMapper sysClientMapper;
    @Autowired
    private FastGptTopicService fastGptTopicService;

    /**
     * 发送聊天请求到API。
     *
     * @param chatRequest 包含聊天请求信息的对象
     */
    public ResponseEntity<String> sendChatRequest(ChatRequest chatRequest) {
        setDefaultValues(chatRequest);
        // 聊天API的URL
        String url = chatConfig.getUrl()+ ApiEndpoint.CHAT_COMPLETIONS.getPath();

        // 设置HTTP请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", chatConfig.getAuthorization());

        // 创建HTTP请求实体
        HttpEntity<ChatRequest> entity = new HttpEntity<>(chatRequest, headers);

        // 使用RestTemplate发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        log.info("准备调用接口");
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("调用完成，响应结果: {}", responseEntity.getBody());
        return responseEntity;
    }

    /**
     * 设置ChatRequest的默认值。
     *
     * @param chatRequest 传入的ChatRequest对象
     * @return 设置默认值后的ChatRequest对象
     */
    public ChatRequest setDefaultValues(ChatRequest chatRequest) {
        if (chatRequest == null) {
            chatRequest = new ChatRequest();
        }
        String temporaryAccess = SpConfigUtil.getConfigValue("temporaryAccess", null);
        if (Boolean.valueOf(temporaryAccess)) {
            chatRequest.setChatId(null);
            chatRequest.setResponseChatItemId(null);
        }

        if (null == chatRequest.getStream()) {
            String stream = SpConfigUtil.getConfigValue("stream", null);
            chatRequest.setStream(Boolean.valueOf(stream));
        }

        if (null == chatRequest.getDetail()) {
            String detail = SpConfigUtil.getConfigValue("detail", null);
            chatRequest.setDetail(Boolean.valueOf(detail));
        }

        return chatRequest;
    }

    /**
     * 获取或创建话题
     *
     * @param chatId 话题ID
     * @param userId 用户ID
     * @param platformId 平台ID
     * @param question 问题
     * @return 操作结果
     */
    public AjaxJson getOrCreateTopic(String chatId, Long userId, Long platformId, String question) {
        QueryWrapper<FastGptTopic> queryWrapper = Wrappers.query();
        queryWrapper.lambda()
                .eq(FastGptTopic::getChatId, chatId);

        // 查找已存在的话题
        FastGptTopic existingTopic = fastGptTopicService.getOne(queryWrapper);

        if (existingTopic != null) {
            return AjaxJson.getSuccessData(existingTopic.getChatId()); // 返回已存在的话题ID
        }

        return createTopic(chatId, userId, platformId, question);
    }

    /**
     * 创建新话题
     *
     * @param userId 用户ID
     * @param platformId 平台ID
     * @param question 问题
     * @return 操作结果
     */
    public AjaxJson createTopic(String chatId, Long userId, Long platformId, String question) {
        // 检查用户话题数量是否超过限制
        long topicCount = fastGptTopicService.count(Wrappers.lambdaQuery(FastGptTopic.class)
                .eq(FastGptTopic::getUserId, userId)
                .eq(FastGptTopic::getPlatformId, platformId));

        if (topicCount >= 10) {
            return AjaxJson.getError("您已超过十个话题");
        }

        // 创建新话题
        FastGptTopic newTopic = new FastGptTopic();
        newTopic.setChatId(chatId);
        newTopic.setTopicName(question);
        newTopic.setPlatformId(platformId);
        newTopic.setUserId(userId);
        fastGptTopicService.save(newTopic);
        return AjaxJson.getSuccessData(newTopic.getChatId()); // 返回新创建的话题ID
    }


    /**
     * 获取知识库详情。
     *
     * @param knowledgeBaseId 知识库ID
     * @return 知识库详情
     */
    public AjaxJson getKnowledgeBaseDetails(String knowledgeBaseId) {
        // 构建API URL
        String url = chatConfig.getUrl() + ApiEndpoint.CORE_DATASET_DETAIL.getPath() + "?id=" + knowledgeBaseId;

        // 设置HTTP请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + chatConfig.getAuthorization());

        // 创建HTTP请求实体
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 使用RestTemplate发送GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        // 解析响应
        String responseStr = responseEntity.getBody();
        if (responseStr != null) {
            return AjaxJson.getSuccessData(responseStr);
        } else {
            return AjaxJson.getError("获取知识库详情失败");
        }
    }
}
